<template>
    <div>
        <el-dialog :title="isEdit ? '修改餐品' : '新增餐品'" :visible.sync="localFormVisible" :before-close="closeDialog" width="40%" :close-on-click-modal="false">
            <el-form :model="mealForm" :rules="rules" ref="formRef">
                <el-form-item v-if="isEdit" label="餐品编号" :label-width="formLabelWidth" prop="mealId">
                    <el-input v-model="mealForm.mealId" autocomplete="off" readonly></el-input>
                </el-form-item>
                <el-form-item label="餐品名称" :label-width="formLabelWidth" prop="mealName">
                    <el-input v-model="mealForm.mealName" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="餐品单价" :label-width="formLabelWidth" prop="price">
                    <el-input v-model="mealForm.price" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="餐品图片" :label-width="formLabelWidth" prop="imageUrl" style="width: 50px; height: 50px;">
                    <el-upload
                        name="image"
                        class="avatar-uploader"
                        action="http://localhost:8086/uploadImg"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                        ref="upload">
                        <img v-if="mealForm.imageUrl" :src="require('@/assets/images/' + mealForm.imageUrl)" class="avatar" alt="" style="width: 100px; height: 100px;">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="closeDialog">关闭</el-button>
                <el-button type="primary" @click="saveForm">保存</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
export default {
    name: "MealForm",
    data(){
        return{
            //表单元素宽度
            formLabelWidth: '120px',
            localFormVisible: this.formVisible,
            imageUrl:'', // 单独的图片 URL 数据
            rules: {
                mealName: [{ required: true, message: '请输入餐品名称', trigger: 'blur' },
                    { validator: this.validateMealName, trigger: 'change' }/*验证餐品重复*/],
                price: [
                    { required: true, message: '请输入餐品单价', trigger: 'blur' },
                    { validator: this.validatePrice, trigger: 'blur' } // 添加自定义验证
                ],
                imageUrl: [{ required: true, message: '请上传餐品图片', trigger: 'change' }]
            }
        }
    },
    methods: {
        closeDialog() {
            this.localFormVisible = false;
            this.$emit('update:formVisible', false)
        },
        saveForm() {
            this.$refs['formRef'].validate((valid) => {
                if (valid) {
                    this.$emit('submitForm', this.mealForm)
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        //上传成功后将图片路径设置为mealForm中的数据
        handleAvatarSuccess(resp) {
            this.mealForm.imageUrl = `${resp}`
        },
        //验证输入价格
        validatePrice(rule, value, callback) {
            const pricePattern = /^\d+(\.\d{1,2})?$/; // 正则表达式：非负数，最多两位小数
            if (!value) {
                return callback(new Error('请输入餐品单价'));
            } else if (!pricePattern.test(value)) {
                return callback(new Error('餐品单价必须为数字，且最多两位小数'));
            }
            callback(); // 验证通过
        },
        //验证餐品名称是否重复
        async validateMealName(rule, value, callback){
            if (!value) {
                callback(new Error('请输入餐品名称'));
            } else {
                try {
                    if (this.isEdit){
                        const originalMeal = (await this.$http.post('/getMealById/' + this.mealForm.mealId)).data
                        if (originalMeal.mealName !==value){
                            const response = await this.$http.post('/checkMealName/' + value);
                            if (response.data) {
                                callback(new Error('餐品名称已存在'));
                            } else {
                                callback();
                            }
                        }
                    }else {
                        const response = await this.$http.post('/checkMealName/' + value);
                        if (response.data) {
                            callback(new Error('餐品名称已存在'));
                        } else {
                            callback();
                        }
                    }
                } catch (error) {
                    console.error('验证时出错:', error);
                    callback(new Error('验证时出错，请稍后再试'));
                }
            }
        }

    },
    props: {
        isEdit: {
            type: Boolean,
            default: false
        },
        formVisible: {
            type: Boolean,
            default: false
        },
        mealForm: Object, // 直接使用父组件传入的 mealForm
    },
    watch: {
        formVisible(newVal) {
            this.localFormVisible = newVal;
            if (newVal && this.$refs['formRef']) {
                this.$refs['formRef'].resetFields();
            }
        }
    },
}
</script>
